package com.shaozi.nc.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.shaozi.lib.logger.DBLogger;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.utils.common.DebugConfigHelper;
import com.shaozi.utils.common.JsonUtil;

@Component
@Aspect
public class RpcServerLogAop {
	@Autowired
	private DBLogger dbLogger;
	@Autowired
	private DebugConfigHelper debugHelper;

	public RpcServerLogAop() {
	}

	@Pointcut(value = "execution(public * com.shaozi.nc.server.rpc.*RpcServer.*(..))")
	public void cutExecute() {
		// logger.debug("point cut");
	}

	@Around("cutExecute()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		long diff = System.currentTimeMillis();
		try {
			Object ret = pjp.proceed();
			saveRetLog(pjp, ret, diff);
			return ret;
		} catch (Exception e) {
			saveThrowingLog(pjp, e, diff);
			throw e;
		}
	}

	private void saveRetLog(ProceedingJoinPoint pjp, Object ret, long diff) {
		if (!debugHelper.isWarnEnable())
			return;
		if (pjp.getArgs().length == 0)
			return;

		Object arg = pjp.getArgs()[0];
		String logType = pjp.getSignature().getName();

		String className = pjp.getTarget().getClass().getSimpleName();

		String logText = JsonUtil.toJsonString(arg);
		String extraId = JsonUtil.toJsonString(ret);
		dbLogger.save(className, logType, logText, extraId, (int) (System.currentTimeMillis() - diff));
	}

	private void saveThrowingLog(ProceedingJoinPoint pjp, Exception e, long diff) {
		if (!debugHelper.isWarnEnable())
			return;
		if (pjp.getArgs().length == 0)
			return;
		Object arg = pjp.getArgs()[0];
		String logType = pjp.getSignature().getName();
		String logText = JsonUtil.toJsonString(arg);
		String extraId = JsonUtil.toJsonString(SzException.getStackMessage(e));
		String className = pjp.getTarget().getClass().getSimpleName();
		dbLogger.save(className, logType, logText, extraId, (int) (System.currentTimeMillis() - diff));
	}
}
